package org.travel_system.controller;

import jakarta.validation.constraints.Pattern;
import org.travel_system.pojo.Admin;
import org.travel_system.service.AdminService;
import org.travel_system.utils.Result;
import org.travel_system.pojo.User;
import org.travel_system.service.UserService;
import org.travel_system.utils.JwtUtil;
import org.travel_system.utils.Md5Util;
import org.travel_system.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    private final UserService userService;
    private final AdminService adminService;

    @Autowired
    public UserController(UserService userService, AdminService adminService){
        this.userService=userService;
        this.adminService=adminService;
    }

    @PostMapping("/register")
    public Result<?> register(@Pattern(regexp = "^\\S{5,16}$") String username,
                           @Pattern(regexp = "^\\S{5,16}$") String password)
    {
        //查询用户
        User u = userService.findUserByName(username);
        Admin admin = adminService.findAdminByName(username);
        if (u == null && admin == null) {
            //注册
            userService.register(username, password);
            return Result.success();
        }else{
            //已有
            return Result.error("用户名已被占用");
        }
    }

    @PostMapping("/login")
    public Result<?> login(@Pattern(regexp = "^\\S{5,16}$") String username,
                        @Pattern(regexp = "^\\S{5,16}$") String password)
    {
        //查询
        User loginUser = userService.findUserByName(username);
        //用户是否存在
        if (loginUser == null) {
            return Result.error("用户名错误");
        }
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            //登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);

            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @GetMapping("/info")
    public Result<User> getUserInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findUserByName(username);
        return Result.success(user);
    }

    @PutMapping("/info")
    public Result<?> updateUserInfo(@RequestBody @Validated User user) {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        Integer userId = userService.findUserId(username);
        userService.update(userId, user);
        return Result.success();
    }

    @PatchMapping("/password")
    public Result<?> updatePwd(@RequestBody Map<String, String> params) {
        //校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要的参数");
        }

        //原密码是否正确
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findUserByName(username);
        if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码错误");
        }

        //原密码和新密码是否一致
        if(loginUser.getPassword().equals(Md5Util.getMD5String(newPwd))){
            return Result.error("原密码和新密码不能一样");
        }

        //newPwd和rePwd是否一样
        if (!rePwd.equals(newPwd)){
            return Result.error("两次填写的新密码不一样");
        }

        //密码更新
        Integer userId = userService.findUserId(username);
        userService.updatePwd(userId, newPwd);
        return Result.success();
    }

    @GetMapping("/id")
    public Result<Integer> getId(@RequestHeader("Authorization") String token) {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        return Result.success(userService.findUserId(username));
    }
}
